package GDoc::Logger;

use Moose;
use File::Path 'make_path';
use File::Basename 'dirname';

has 'jobclass'  => ( is       => 'ro',
                     isa      => 'Str' 
                   );


my $BASE_DIR = '/govdoc/logs/';

my %FH_CACHE;

sub get_logger {
    my $class = shift;
    my %args = @_;

    my ( $jobclass ) = (caller)[0];

    if ( $args{reopen} ) { 
        my $logfile = $class->_logfile( $jobclass );
        delete $FH_CACHE{$logfile}
    }

    return $class->new( jobclass => $jobclass );
}


sub _logfile { 
    my $inv = shift;
    my $jobclass = shift;

    my $logfile = $BASE_DIR . ( join '/', map { lc } split /::/, $jobclass ) . '.log';
    return $logfile;
}

foreach my $level( qw{trace info warn error fatal} ) { 
    my $meth = sub { 
        my $self = shift;
        my $msg = shift;

        my @now = localtime;

        my $logfile = $self->_logfile( $self->jobclass );
        my $fh;
        $fh = $FH_CACHE{$logfile} or do { 
            my $dir = dirname $logfile;
            make_path( $dir, { mode => 0755 } ) unless -d $dir;
            open $fh, '>>', $logfile or die "Can't open log file $logfile: $!";
            binmode $fh, ':utf8';
            $FH_CACHE{$logfile} = $fh;
        };

        select do { 
            my $oldfh = select $fh;
            $| = 1;
            $oldfh;
        };

        printf $fh "[%02d-%02d-%02d %02d:%02d:%02d %-6s %5d] %s\n", 
          ( $now[5] + 1900 ), @now[4, 3, 2, 1, 0], uc( $level ), $$, $msg;
    };

    no strict 'refs';
    *{ $level } = $meth;
}



1;

